from django.http.response import JsonResponse
from .models import *
from rest_framework.response import Response
from rest_framework.views import APIView
from .ser import *
# Create your views here.
def cate_get(request):
    cates = Cate.objects.all()
    data = [
        {
            'id':i.id,
            'name':i.name
        }
        for i in cates
    ]
    return JsonResponse(data,safe=False)
def cate_post(request):
    id = request.POST.get('id')
    name = request.POST.get('name')
    if not all([id,name]):
        return JsonResponse({'msg':'缺少参数'},status=404)
    try:
        Cate.objects.create(id=id,name=name)
    except Exception as e:
        print(e)
        return JsonResponse({'msg':'添加失败'},status=500)
    return JsonResponse({'msg': '添加成功'},status=201)
def book_get(request):
    books = Book.objects.all()
    data = [
        {
            'id':i.id,
            'name':i.name,
            'sale':i.sale,
            'price':i.price,
            'date':i.date,
            'cate_id':i.cate_id
        }
        for i in books
    ]
    return JsonResponse(data,safe=False)
def book_post(request):
    id = request.POST.get('id')
    name = request.POST.get('name')
    sale = request.POST.get('sale')
    price = request.POST.get('price')
    date = request.POST.get('date')
    cate_id = request.POST.get('cate_id')
    if not all([id,name,sale,price,date,cate_id]):
        return JsonResponse({'msg': '缺少参数'}, status=404)
    try:
        Book.objects.create(id=id,name=name,sale=sale,price=price,date=date,cate_id=cate_id)
    except Exception as e:
        print(e)
        return JsonResponse({'msg': '添加失败'}, status=500)
    return JsonResponse({'msg': '添加成功'}, status=201)